package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"time"
	"zy5_novel/cache"
	"zy5_novel/models"
	"zy5_novel/pkg"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	var err error

	account := c.GetString("account")
	password := c.GetString("password")

	if account == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "参数不能为空",
		}
		c.ServeJSON()
		return
	}

	var user models.User
	user.Account = account
	user.Password = pkg.Md5(password)

	if err = user.GetAccountByAccount(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if user.ID != 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户已存在",
		}
		c.ServeJSON()
		return
	}

	if err = user.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "注册失败",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "注册成功",
	}
	c.ServeJSON()
}

func (c *UserController) Login() {
	var err error

	account := c.GetString("account")
	password := c.GetString("password")

	if account == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "参数不能为空",
		}
		c.ServeJSON()
		return
	}

	key := "password_err_" + account
	count, _ := cache.Rdb.Get(cache.Ctx, key).Int()
	if count >= 2 {
		cache.Rdb.Expire(cache.Ctx, key, time.Hour*3)
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "密码错误次数超过三次，封禁三小时",
		}
		c.ServeJSON()
		return
	}

	var user models.User
	user.Account = account
	user.Password = pkg.Md5(password)

	if err = user.GetAccountByAccount(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统异常",
		}
		c.ServeJSON()
		return
	}

	if user.ID == 0 {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "用户不存在",
		}
		c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, key)
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "密码错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "登陆成功",
	}
	c.ServeJSON()
}
